/**
 * @param {function} fn 需要debounce防抖函数处理的函数
 * @param {number} delay 定时器延时的时间
 */
export function debounce(fn, delay) {
  let timer = null;
  // 该变量常驻内存，可以记住上一次的状态
  // 只有在外层函数失去引用时，该变量才会清除
  // 缓存定时器id

  return (...args) => {
    // 返回一个闭包
    // 注意参数：比如事件对象 event 能够获取到
    if (timer) {
      // timer存在，就清除定时器
      // 清除定时器，则定时器对应的回调函数也就不会执行
      clearTimeout(timer);
    }
    // 清除定时器后，重新计时
    timer = setTimeout(() => {
      fn.call(this, ...args);
      // this需要定时器回调函数时才能确定，this指向调用时所在的对象，大多数情况都指向window
    }, delay);
  };
}

export const canGotoUrl = (url, { readStr, startAnswerStr, endAnswerStr }) => {
  if (readStr === "" || startAnswerStr === "" || endAnswerStr === "")
    return true;
  const readingTime = new Date(readStr);
  const startAnswerTime = new Date(startAnswerStr);
  const endAnswerTime = new Date(endAnswerStr);
  if (
    readingTime === undefined ||
    startAnswerTime === undefined ||
    endAnswerTime === undefined
  ) {
    return;
  }
  const current = Date.now();
  switch (url) {
    case "/":
    case "/rules":
    case "/countdown":
      return true;
    case "/read":
      return +current >= +readingTime && +current < +startAnswerTime;
    case "/quiz":
      return +current >= +startAnswerTime && +current < +endAnswerTime;
    case "/rank":
    case "/certificate":
      return +current >= +endAnswerTime;
    default:
      return false;
  }
};

export const updateRoute = debounce((readStr, startAnswerStr, endAnswerStr) => {
  // console.log(readStr, startAnswerStr, endAnswerStr);
  if (readStr === "" || startAnswerStr === "" || endAnswerStr === "") return;
  const readingTime = new Date(readStr);
  const startAnswerTime = new Date(startAnswerStr);
  const endAnswerTime = new Date(endAnswerStr);
  if (
    readingTime === undefined ||
    startAnswerTime === undefined ||
    endAnswerTime === undefined
  ) {
    return;
  }
  const current = Date.now();
  const href = window.location.href.replace(
    /^https?:\/\/[^/]+(\/[A-Za-z]*)\??/,
    (_, p1) => p1
  );
  // console.log(href);
  // console.log(current, +readingTime, +startAnswerTime, +endAnswerTime);
  if (+current < +readingTime) {
    if (href !== "/" && href !== "/rules") window.location.replace("/");
  } else if (+current < +startAnswerTime) {
    if (href !== "/read") {
      window.location.replace("/read");
    }
  } else if (+current < +endAnswerTime) {
    if (
      href !== "/quiz" &&
      href !== "/countdown" &&
      href !== "/" &&
      href !== "/rules"
    ) {
      window.location.replace("/quiz");
    }
  } else if (
    href !== "/rank" &&
    href !== "/certificate" &&
    href !== "/" &&
    href !== "/rules"
  ) {
    window.location.replace("/rank");
  }
}, 100);
